package security;

import java.io.File;
import java.io.IOException;
import constans.SizeConstans;
import java.io.FileInputStream;
import java.io.BufferedInputStream;
import java.security.MessageDigest;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;


/**
 * This class provides the functionality of a message digest algorithm SHA-1
 * 
 */
public class MessageDigestSHA1{

    /**
     *This MessageDigest object provides applications the functionality of a message digest algorithm
     */
	private MessageDigest md;
    

    /**
     * Class constructor
     *
     * @throws java.security.GeneralSecurityException If an generic security exception error occurs
     */
    public MessageDigestSHA1()
        throws GeneralSecurityException{
		md = MessageDigest.getInstance("SHA-1");
	}

    /**
     *
     * Gets the hash of a file
     * @param file a file
     * @return hash of the file
     * @throws java.io.IOException If an I/O error occurs
     */
    public byte[] digest(File file)
        throws IOException{

		BufferedInputStream stream = null;

		try {

			stream = new BufferedInputStream(new FileInputStream(file));

			int num = 0;
			byte [] buffer = new byte[(int)SizeConstans.KByte];

			md.reset();		

			while ((num = stream.read(buffer)) >= 0)
				md.update(buffer, 0, num);

			stream.close();
			stream = null;

			return md.digest(); 

		} catch (IOException e) {
			try {
				if(stream!=null){
					stream.close();
					stream = null;
				}
			} catch (IOException e1) {}
			throw new IOException(e);
		}
	}

    /**
     * Gets the hash of a string
     * @param str a string
     * @return hash of the string
     * @throws java.io.UnsupportedEncodingException If the Character Encoding is not supported
     */
    public byte[] digest(String str)
        throws UnsupportedEncodingException{

		md.reset();

		return md.digest(str.getBytes("UTF-8"));
	}

}